package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"loveserver/errno"
	"loveserver/model"
	"loveserver/utils"
	"strconv"
)

type ListAdvice struct {
	Total    uint64              `json:"total"`
	DataList []model.AdviceModel `json:"dataList"`
}

type EmailFeedBack struct {
	Email    string `json:"email"`
	Headline string `json:"headline"`     //邮件反馈的标题和内容
    Body     string `json:"body"`
}


type createAdvice struct {
}

/*advice 路由相关处理函数*/

// * get all advice api.
func FetchAllAdvice(c *gin.Context) {
	var advice model.AdviceModel
	count, advices, err := advice.GetAll()
	if err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}

	SendResponse(c, nil, ListAdvice{
		Total:    count,
		DataList: advices,
	})
}

// get a advice api
func FetchSingleAdvice(c *gin.Context) {
	var advice model.AdviceModel
	var err error
	id, _ := strconv.Atoi(c.Param("id"))
	advice.ID = uint(id)

	if advice, err = advice.Get(); err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}
	SendResponse(c, nil, advice)
}

// create a advice
func AddAdvice(c *gin.Context) {

	advice := model.AdviceModel{
		Email: 	   c.PostForm("email"),
		Title:     c.PostForm("title"),
		Content:   c.PostForm("content"),
	}

	//json绑定
	err :=c.BindJSON(&advice)
	if err!=nil{
		log.Fatal(err.Error())
		return
	}

	// * 创建一条记录，错误处理
	if err := advice.Create(); err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}

	// * 返回结果
	SendResponse(c, nil, "create successful.")
}


// handle a advice 管理员邮件发送反馈
func HandleAdvice(c *gin.Context) {
	// 获取请求体的title和content 然后调用utils的邮件发送功能向用户发送反馈

	//将邮箱反馈结构体与json绑定
	var feedback EmailFeedBack
	err1 :=c.BindJSON(&feedback)
	if err1!=nil{
		log.Fatal(err1.Error())
		return
	}
	//定义收件人
	mailTo := []string{
		feedback.Email,
	}
	//定义邮件主题
	subject := feedback.Headline
	// 邮件正文
	body := feedback.Body

	err := utils.SendMail(mailTo, subject, body)
	if err != nil {
		log.Println(err)
		fmt.Println("send fail")
		SendResponse(c, err, nil)
		return
	}
	// * 返回结果
	SendResponse(c, nil, "the mail successfully send.")
}


// delete a advice
func DeleteAdvice(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	advice := model.AdviceModel{}

	advice.ID = uint(id)

	if err := advice.Delete(); err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}
	SendResponse(c, nil, "delete successful.")
}

